package com.jl.juc.completablefuture;


import org.springframework.util.DigestUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

public class CompletableFutureDemo3 {


    public static String md5(String path) {
        try {
            String md51 = DigestUtils.md5Digest(new FileInputStream(path)).toString();
            return md51;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> batchMd5(List<String> paths) {
        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (String path : paths) {
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> md5(path));
            futures.add(future);
        }
        CompletableFuture<String>[] completableFutures = futures.toArray(new CompletableFuture[futures.size()]);
        CompletableFuture.allOf(completableFutures).join();
        return Arrays.stream(completableFutures).map(completableFuture -> completableFuture.getNow(null)).collect(Collectors.toList());
    }

    public static void main(String[] args) {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("1111");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("6666");
            return "hh";
        });

        System.out.println("222222222");
        String join = completableFuture.join();
        System.out.println("333333333333");

    }

}
